package com.qunar.train.mock.dubbo;

import com.google.common.io.Closer;

import com.qunar.train.mock.util.AegisLog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.annotation.processing.Filer;

import static com.google.common.base.Charsets.UTF_8;
import static com.qunar.train.mock.util.AegisLog.log;

public class DaoMybatisConfigFileCreator {

    public static void addNewPlugsInMybatisXML(Filer filer) {
        /**
         * 1.查找配置文件
         * 2.获取并修改配置文件内容
         * 3.生成新配置文件
         * */
        log("find mybatis config files");
        List mybatisConfigs = new GenerrateClassTool().findConfigFilesReturnFile("<mappers>");

        log("generate config files");
        for (Object file : mybatisConfigs) {
            String content = null;
            try {
                InputStream inputstream = new FileInputStream((File) file);
                content = readAndFilterCommit(inputstream, "<plugins>");
                log(((File) file).getName());
                GenerrateClassTool.createResource(filer, "aegis/dao/" + ((File) file).getName(), content);
            } catch (IOException e) {
                AegisLog.error(e);
            }
        }
    }

    public static String readAndFilterCommit(InputStream input, String flag) throws IOException {
        Closer closer = Closer.create();
        String newString = "<plugins>\n\t\t" +
                "<plugin interceptor=\"com.qunar.train.mock.database.MybatisSqlInterceptorImpl\"/>";
        String oldString = "<plugins>";
        String addString = "<plugins>\n\t\t<plugin interceptor=\"com.qunar.train.mock.database.MybatisSqlInterceptorImpl\"/>\n\t</plugins>\n\n\t";
        try {
            BufferedReader br = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
            String pline = new String("");
            StringBuffer content = new StringBuffer();
            Boolean hasChanged = false;
            while ((pline = br.readLine()) != null) {
                if (pline.indexOf(flag) != -1 && hasChanged == false) {
                    if (pline.indexOf("<!--") != -1 || pline.indexOf("//") != -1) {
                        content.append(pline + "\n");
                        continue;
                    }
                    pline = pline.replace(oldString, newString);
                    hasChanged = true;
                }
                content.append(pline + "\n");
            }
            if (!hasChanged) {
                content = content.insert(content.indexOf("<mappers>"), addString);
            }
            br.close();
            return content.toString();
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    }
}


